package com.itheima.reggie.controller;

import cn.hutool.core.collection.CollUtil;
import com.itheima.reggie.common.Page;
import com.itheima.reggie.entity.DisFlavor;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishDto;
import com.itheima.reggie.entity.Result;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.net.InetAddress;
import java.time.LocalDateTime;
import java.util.List;

@Controller
public class DishController {

    @Autowired
    private DishService dishService ;

    //新增菜品
    @PostMapping("/dish")
    @ResponseBody
    public Result save (@RequestBody DishDto dishDto , HttpSession httpSession ){
        Long employee = (Long) httpSession.getAttribute("employee");
        dishDto.setCreateUser(employee);
        dishDto.setUpdateUser(employee);
        List<DisFlavor> flavors = dishDto.getFlavors();
        if (CollUtil.isNotEmpty(flavors)) {
            for(DisFlavor disFlavor : flavors ){
                disFlavor.setCreateUser(employee);
                disFlavor.setUpdateUser(employee);
            }
        }
        dishService.save(dishDto);
        return Result.success(null);
    }

    @GetMapping("/dish/page")
    @ResponseBody
    public Result findAllDish(Integer page , Integer pageSize , String name ){
        Page<DishDto> allDish = dishService.findAllDish(page, pageSize, name);
        return Result.success(allDish);
    }

    @GetMapping("/dish/{id}")
    @ResponseBody
    public Result findById( @PathVariable Long id  ){
       DishDto dishDto =  dishService.findById(id);
       return Result.success(dishDto);
    }

    @PutMapping("/dish")
    @ResponseBody
    public Result update( @RequestBody  DishDto dishDto , HttpSession httpSession ){
        Long employee = (Long) httpSession.getAttribute("employee");
        dishDto.setUpdateUser(employee);
        dishService.update(dishDto);
        return Result.success(null);
    }

    @GetMapping("/dish/list")
    @ResponseBody
    public Result findByCategoryId( Long categoryId ){
        List<DishDto> byCategoryId = dishService.findByCategoryId(categoryId);
        return Result.success(byCategoryId);
    }

    @PostMapping("/dish/status/{status}")
    @ResponseBody
    public Result status( @PathVariable("status") Integer status ,  Long ids , HttpSession httpSession   ){
        //创建一个菜品实体
        Dish dish = new Dish();
        //为菜品实体赋值
        dish.setStatus(status);
        dish.setId(ids);
        dish.setUpdateUser((Long) httpSession.getAttribute("employee"));
        dish.setUpdateTime(LocalDateTime.now());
        dishService.status( dish );
        return Result.success(null);

    }


}
